#!/usr/bin/env python
#coding=utf-8

from flask import Blueprint, session, request, render_template, make_response, g, url_for
from flask.ext.sqlalchemy import Pagination

from aladin.database import db
from aladin.helpers import toint, get_count, log_info, show_admin_success

from app.models.user import User, UserImage
from app.models.teacher import Teacher, TeacherCat, TeacherGoods, TeacherRegion

from app.services.yunpian import YunPian
from app.services.push import XingePushService

teacher = Blueprint('teacher', __name__)


@teacher.route('/')
@teacher.route('/<int:page>')
@teacher.route('/<int:page>-<int:page_size>')
def index(page=1, page_size=20):
    """老师列表"""
    g.title     = u'老师列表'
    g.page_type = 'search'

    args     = request.args
    uid      = toint(args.get('uid', '0'))
    mobile   = args.get('mobile', '')
    realname = args.get('realname', '')

    q = Teacher.query
    if uid > 0:
        q = q.filter(Teacher.uid == uid)

    if mobile:
        user = User.query.filter(User.mobile == mobile).first()
        if user is not None:
            q = q.filter(Teacher.uid == user.uid)

    if realname:
        q = q.filter(Teacher.realname == realname)

    teacher_count = get_count(q)
    teacher_list = q.order_by(Teacher.uid.desc()).offset((page-1)*page_size).\
                    limit(page_size).all()
    pagination  = Pagination(None, page, page_size, teacher_count, None)

    res = make_response(render_template('teacher/index.html', 
            teacher_list=teacher_list, pagination=pagination))
    res.set_cookie('goback_url', request.url)
    return res


@teacher.route('/detail/<int:uid>', methods=['GET', 'POST'])
def detail(uid):
    """老师详情"""
    g.title = u'老师详情'
    g.page_type = ''

    t = Teacher.query.get_or_404(uid)
    user = User.query.get_or_404(uid)

    if request.method == 'GET':
        ui_list = UserImage.query.filter(UserImage.uid == uid).all()
        tr_list = TeacherRegion.query.filter(TeacherRegion.uid == uid).all()
        tg_list = TeacherGoods.query.filter(TeacherGoods.uid == uid).all()
        return render_template('teacher/detail.html', teacher=t, user=user,
            ui_list=ui_list, tr_list=tr_list, tg_list=tg_list)

    form = request.form
    nickname   = form.get('nickname', '')
    realname   = form.get('realname', '')
    gender     = toint(form.get('gender', '0'))
    birth_year = toint(form.get('birth_year', '0'))
    id_no      = form.get('id_no', '')
    signature  = form.get('signature', '')
    cert_tags  = form.get('cert_tags', '')
    is_display = toint(form.get('is_display', '0'))

    old_is_display = t.is_display

    t.nickname   = nickname
    t.realname   = realname
    t.gender     = gender
    t.birth_year = birth_year
    t.id_no      = id_no
    t.signature  = signature
    t.cert_tags  = cert_tags
    t.is_display = is_display

    user.nickname   = nickname
    user.realname   = realname
    user.gender     = gender
    user.birth_year = birth_year
    user.id_no      = id_no
    user.signature  = signature

    db.session.commit()

    # 审核通过
    if old_is_display == 0 and is_display == 1:
        content = u'恭喜您成为私享课认证导师！更新私享课1.0.7最新版本，开通"我的钱包"马上获得50元可提现现金红包！'
        sms_content = u'恭喜您成为私享课认证导师！更新私享课1.0.7最新版本，开通"我的钱包"马上获得50元可提现现金红包！【私享课】'
        sms = YunPian()
        res = sms.send_sms_text(user.mobile, sms_content)
        log_info(res)

        push = XingePushService()
        push.push_user(user.uid, u'私享课', content)

    dump_url = request.cookies.get('goback_url', url_for('teacher.index'))
    return show_admin_success(u'老师', u'编辑老师成功', dump_url, 3)
